using APP.HELPER.Data.Helper;
using APP.HELPER.Utils;
using APP.HELPER.Utils.CustomizeToolbox;
using APP.HELPER.Utils.Security;
using DevExpress.XtraEditors;
using Extra.Common;
using System;
using System.Data;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
namespace Extra.Data.Extra.Class
{
    public class MyLogon
    {
        private readonly string _serverParameters = (Application.StartupPath + @"\Data.config.xml");

        public event ErrorEventHander Error;

        public event FailEventHander Fail;

        public event FinishEventHander Finish;

        public event FirstEventHander First;

        public void Execute()
        {
            this.Execute(Environment.MachineName.ToUpper() + @"\PERFECT", "ERP." + GridCalendarControlLib.SignSoft(), "sa", "perfect", true, DataController.DataMaker.GetLastDrive() + @"\Database\Perfect Software\" + AssemblyHelper.AssemblyTradeMark);
        }

        public void Execute(string server, string database, string userid, string password, bool authencation, string primarypath)
        {
            this.Maker(server, database, userid, password, authencation, primarypath);
        }

        public void Execute2(string server, string database, string userid, string password, bool authencation, string primarypath, bool example)
        {
            this.Maker2(server, database, userid, password, authencation, primarypath, example);
        }

        public void FirstRun()
        {
            FileInfo info = new FileInfo(this._serverParameters);
            if (!info.Exists)
            {
                new xfmFirstRunConfig().ShowDialog();
            }
            else
            {
                this.RaiseFinishEventHander(this.ReadCofig());
            }
        }

        private void Maker(string server, string database, string userid, string password, bool authencation, string primarypath)
        {
            SqlHelper helper = new SqlHelper(server, database, userid, password, authencation);
            helper.Extract();
            string message = DataController.DataMaker.Maker(helper.Server, helper.UserID, helper.Password, database, primarypath, authencation);
            if (message != "OK")
            {
                this.RaiseErrorEventHander(message);
            }
            else
            {
                this.SaveConfig(helper.Server, authencation ? 0 : 1, helper.UserID, helper.Password, helper.Database);
                this.RaiseFirstEventHander(helper.ConnectionString, "");
            }
        }

        private void Maker2(string server, string database, string userid, string password, bool authencation, string primarypath, bool example)
        {
            int num = 0;
            SqlHelper helper = new SqlHelper(server, database, userid, password, authencation);
            helper.Extract();
            string message = DataController.DataMaker.Maker(helper.Server, helper.UserID, helper.Password, database, primarypath, authencation);
            SqlHelper.ConnectString = helper.ConnectionString;
            if (message != "OK")
            {
                this.RaiseErrorEventHander(message);
            }
            else
            {
                if (message == "OK")
                {
                    num++;
                }
                if (example)
                {
                    helper = new SqlHelper(server, "HRMExample", userid, password, authencation);
                    helper.Extract();
                    message = DataController.DataMaker.MakerExample(helper.Server, helper.UserID, helper.Password, "HRMExample", primarypath, authencation);
                    if ((message == "OK") && (message == "OK"))
                    {
                        num++;
                    }
                }
                if (num >= 1)
                {
                    this.SaveConfig(helper.Server, authencation ? 0 : 1, helper.UserID, helper.Password, helper.Database);
                    this.RaiseFirstEventHander(SqlHelper.ConnectString, "");
                    if (num == 2)
                    {
                        this.SaveConfig(helper.Server, authencation ? 0 : 1, helper.UserID, helper.Password, "HRMExample");
                        SqlHelper.ConnectString = helper.ConnectionString;
                    }
                }
                else
                {
                    this.RaiseErrorEventHander(message);
                }
            }
        }

        private void RaiseErrorEventHander(string message)
        {
            if (this.Error != null)
            {
                this.Error(this, message);
            }
        }

        private void RaiseFailEventHander()
        {
            if (this.Fail != null)
            {
                this.Fail(this);
            }
        }

        private void RaiseFinishEventHander(string connecstring)
        {
            if (this.Finish != null)
            {
                this.Finish(this, connecstring);
            }
        }

        private void RaiseFirstEventHander(string connectString, string database)
        {
            if (this.First != null)
            {
                this.First(this, connectString, database);
            }
        }

        private string ReadCofig()
        {
            DataTable table = new DataTable("SERVER");
            table.Columns.Add("server");
            table.Columns.Add("auth");
            table.Columns.Add("user");
            table.Columns.Add("pass");
            table.Columns.Add("database");
            table.Columns.Add("ConnectString");
            FileInfo info = new FileInfo(this._serverParameters);
            if (info.Exists)
            {
                DataSet set = new DataSet();
                set.Tables.Add(table);
                set.ReadXml(this._serverParameters);
                try
                {
                    if (set.Tables[0].Rows.Count > 0)
                    {
                        SqlHelper.ConnectString = MyEncryption.Decrypt(set.Tables[0].Rows[0]["ConnectString"].ToString(), "963147", true);
                        return SqlHelper.ConnectString;
                    }
                    XtraMessageBox.Show("Kh\x00f4ng t\x00ecm thấy cấu h\x00ecnh kết nối đến m\x00e1y chủ.\nVui l\x00f2ng cấu h\x00ecnh lại m\x00e1y chủ.", "Th\x00f4ng b\x00e1o", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    new xfmDatabaseConfig().ShowDialog();
                }
                catch (Exception exception)
                {
                    XtraMessageBox.Show(exception.Message, "Th\x00f4ng b\x00e1o", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    this.RaiseErrorEventHander(exception.Message);
                }
            }
            return "";
        }

        public void SaveConfig(string server, int auth, string user, string pass, string database)
        {
            try
            {
                string toEncrypt = new SqlHelper().RebuildConnectionString(server, database, user, pass, auth == 0);
                DataSet set = new DataSet();
                DataTable table = new DataTable("SERVER");
                table.Columns.Add("server");
                table.Columns.Add("auth");
                table.Columns.Add("user");
                table.Columns.Add("pass");
                table.Columns.Add("database");
                table.Columns.Add("ConnectString");
                table.Rows.Clear();
                table.Rows.Add(new object[] { server, auth, MyEncryption.Encrypt(user, "963147", true), MyEncryption.Encrypt(pass, "963147", true), database, MyEncryption.Encrypt(toEncrypt, "963147", true) });
                set.Tables.Add(table);
                set.WriteXml(this._serverParameters);
            }
            catch (Exception exception)
            {
                XtraMessageBox.Show(exception.Message, "Th\x00f4ng B\x00e1o", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        public delegate void ErrorEventHander(object sender, string message);

        public delegate void FailEventHander(object sender);

        public delegate void FinishEventHander(object sender, string connecstring);

        public delegate void FirstEventHander(object sender, string connectString, string database);
    }

}
